﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Globalization;
using System.IO;

namespace AccidentCards
{
    public partial class AccidentCardForm : Form
    {
        private long accidentCardId = -1;
        private Bitmap frontPage;
        private Bitmap backPage;
        private ImageForm imageViewer;

        private Dictionary<int, int> vehicle_Map = new Dictionary<int, int>();
        private Dictionary<int, int> person_Map = new Dictionary<int, int>();

        public AccidentCardForm()
        {
            InitializeComponent();
            //frontPage = new Bitmap("_DSC3611_2681.JPGf4.jpg");

        }
        public AccidentCardForm( long cardID )
        {
            InitializeComponent();
            accidentCardId = cardID;
            //frontPage = new Bitmap("_DSC3611_2681.JPGf4.jpg");
        }


        private void LoadComboBoxes()
        {
            Dictionary.LoadComboBoxValues(operationType, Dictionary.DictCategories.OperationTypes);
            Dictionary.LoadComboBoxValues(roadName, Dictionary.DictCategories.RoadNames);
            Dictionary.LoadComboBoxValues(roadValue, Dictionary.DictCategories.RoadValues);
            Dictionary.LoadComboBoxValues(roadCategory, Dictionary.DictCategories.RoadCategories);
            Dictionary.LoadComboBoxValues(region, Dictionary.DictCategories.Regions);
            Dictionary.LoadComboBoxValues(centerOfPopulationName, Dictionary.DictCategories.CenterOfPopulationNames);
            Dictionary.LoadComboBoxValues(centerOfPopulationStatus, Dictionary.DictCategories.CenterOfPopulationSatuses);
            Dictionary.LoadComboBoxValues(streetName, Dictionary.DictCategories.StreetNames);
            Dictionary.LoadComboBoxValues(streetCategory, Dictionary.DictCategories.StreetCategory);
            Dictionary.LoadComboBoxValues(accidentType, Dictionary.DictCategories.AccidentTypes);
            Dictionary.LoadComboBoxValues(accidentScheme, Dictionary.DictCategories.AccidentSchemes);
            Dictionary.LoadComboBoxValues(planElement, Dictionary.DictCategories.PlanElements);
            Dictionary.LoadComboBoxValues(engineeringStructure, Dictionary.DictCategories.EngineeringStructures);
            Dictionary.LoadComboBoxValues(coverType, Dictionary.DictCategories.CoverTypes);
            Dictionary.LoadComboBoxValues(roadState, Dictionary.DictCategories.RoadStates);
            Dictionary.LoadComboBoxValues(lightType, Dictionary.DictCategories.LightTypes);
            Dictionary.LoadComboBoxValues(whetherType, Dictionary.DictCategories.WhetherTypes);
            Dictionary.LoadComboBoxValues(roadCondition, Dictionary.DictCategories.RoadConditions); 
        }

        private void LoadVehicleList(long id)
        {
            lbCars.Items.Clear();
            vehicle_Map.Clear();
            DataTable carsList = VehicleCard.GetAllVehicle(id);
            for (int i = 0; i < carsList.Rows.Count; ++i)
            {
                string manInfo = String.Format("Автомобиль гос. номер - {0}",
                                              carsList.Rows[i]["carIdNumber"].ToString());

                vehicle_Map.Add(lbCars.Items.Count, Convert.ToInt32(carsList.Rows[i]["VehicleId"]));
                lbCars.Items.Add(manInfo);
            }
        }

        private void LoadPersonList(long id)
        {
            lbPeople.Items.Clear();
            person_Map.Clear();
            DataTable personList = PersonCard.GetAllPerson(id);
            for (int i = 0; i < personList.Rows.Count; ++i)
            {
                string manInfo = String.Format("Участник ДТП - {0}",
                                              personList.Rows[i]["fullName"].ToString());

                person_Map.Add(lbPeople.Items.Count, Convert.ToInt32(personList.Rows[i]["PersonId"]));
                lbPeople.Items.Add(manInfo);
            }
        }

        private void LoadFirstPage(long id)
        {
            using (SqlConnection m_connection = new SqlConnection(dbServices.globalConnectionString))
                try
                {
                    DataTable dtCard;
                    dtCard = AccidentCard.GetAccidentCardInfoById(id);
                    regionCode.Text = dtCard.Rows[0]["regionCode"].ToString();
                    accidentDate.Value = Convert.ToDateTime(dtCard.Rows[0]["accidentDateTime"]);
                    accidentTime.Value = Convert.ToDateTime(dtCard.Rows[0]["accidentDateTime"]);
                    operationType.SelectedValue = Convert.ToInt32(dtCard.Rows[0]["operationType"]);
                    cardRegistrationNumber.Text = dtCard.Rows[0]["cardRegistrationNumber"].ToString();
                    checksum.Text = dtCard.Rows[0]["checksum"].ToString();
                    cardReportNumber.Text = dtCard.Rows[0]["cardReportNumber"].ToString();
                    streetName.SelectedValue = Convert.ToInt32(dtCard.Rows[0]["streetName"]);
                    streetCategory.SelectedValue = Convert.ToInt32(dtCard.Rows[0]["streetCategory"]);
                    house.Text = dtCard.Rows[0]["house"].ToString();
                    distanceM.Text = dtCard.Rows[0]["distanceM"].ToString();
                    distanceKm.Text = dtCard.Rows[0]["distanceKm"].ToString();
                    centerOfPopulationName.SelectedValue = Convert.ToInt32(dtCard.Rows[0]["centerOfPopulationName"]);
                    centerOfPopulationStatus.SelectedValue = Convert.ToInt32(dtCard.Rows[0]["centerOfPopulationStatus"]);
                    roadCategory.SelectedValue = Convert.ToInt32(dtCard.Rows[0]["roadCategory"]);
                    region.SelectedValue = Convert.ToInt32(dtCard.Rows[0]["region"]);
                    roadName.SelectedValue = Convert.ToInt32(dtCard.Rows[0]["roadName"]);
                    roadValue.SelectedValue = Convert.ToInt32(dtCard.Rows[0]["roadValue"]);
                    participentAmmount.Text = dtCard.Rows[0]["participentAmmount"].ToString();
                    vehicleAmmount.Text = dtCard.Rows[0]["vehicleAmmount"].ToString();
                    accidentScheme.SelectedValue = Convert.ToInt32(dtCard.Rows[0]["accidentScheme"]);
                    accidentType.SelectedValue = Convert.ToInt32(dtCard.Rows[0]["accidentType"]);
                    centerStripWidth.Text = dtCard.Rows[0]["centerStripWidth"].ToString();
                    sidewalkWidth.Text = dtCard.Rows[0]["sidewalkWidth"].ToString();
                    roadsideWidth.Text = dtCard.Rows[0]["roadsideWidth"].ToString();
                    roadWidth.Text = dtCard.Rows[0]["roadWidth"].ToString();
                    additionalInfo.Text = dtCard.Rows[0]["additionalInfo"].ToString();
                    engineeringStructure.SelectedValue = Convert.ToInt32(dtCard.Rows[0]["engineeringStructure"]);
                    planElement.SelectedValue = Convert.ToInt32(dtCard.Rows[0]["planElement"]);
                    coverType.SelectedValue = Convert.ToInt32(dtCard.Rows[0]["coverType"]);
                    roadState.SelectedValue = Convert.ToInt32(dtCard.Rows[0]["roadState"]);
                    lightType.SelectedValue = Convert.ToInt32(dtCard.Rows[0]["lightType"]);
                    whetherType.SelectedValue = Convert.ToInt32(dtCard.Rows[0]["whetherType"]);
                    roadCondition.SelectedValue = Convert.ToInt32(dtCard.Rows[0]["roadCondition"]);

                    if (!String.IsNullOrEmpty(dtCard.Rows[0]["frontPage"].ToString()))
                    {                        
                        cbHaveFrontImage.Checked = true;
                        frontPage = AccidentCard.GetFrontImage(accidentCardId);                                              
                    }
                    if (!String.IsNullOrEmpty(dtCard.Rows[0]["backPage"].ToString()))
                    {                       
                        cbHaveBackImage.Checked = true;
                        backPage = AccidentCard.GetBackImage(accidentCardId);
                    }    
                }
                catch
                {
                    MessageBox.Show("Ошибка в  LoadFirstPage");
                }

        }

        private void LoadAccidentCard(long id)
        {
            LoadFirstPage(id);
            LoadVehicleList(id);
            LoadPersonList(id);
        }


        private void AccidentCard_Load(object sender, EventArgs e)
        {
            LoadComboBoxes();
            if (accidentCardId != -1)
            {
                LoadAccidentCard(accidentCardId);
            }
            imageViewer = new ImageForm();
            imageViewer.Show();
   
        }

        

        private void btnClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            if (accidentCardId == -1)
            {
                AccidentCard.CreateAccidentCard(ref accidentCardId);
            }

            DateTime accidentDateTime = new DateTime(accidentDate.Value.Year, accidentDate.Value.Month, accidentDate.Value.Day,
                                                  accidentTime.Value.Hour, accidentTime.Value.Minute, accidentTime.Value.Second);
            AccidentCard.UpdateAccidentCard(accidentCardId,
                                          Convert.ToInt32(regionCode.Text),
                                          accidentDateTime,
                                          Convert.ToInt32(operationType.SelectedValue),
                                          Convert.ToInt32(cardRegistrationNumber.Text),
                                          Convert.ToInt32(checksum.Text),
                                          Convert.ToInt32(cardReportNumber.Text),
                                          Convert.ToInt32(streetName.SelectedValue),
                                          Convert.ToInt32(streetCategory.SelectedValue),
                                          house.Text,
                                          Convert.ToInt32(distanceM.Text),
                                          Convert.ToInt32(distanceKm.Text),
                                          Convert.ToInt32(centerOfPopulationName.SelectedValue),
                                          Convert.ToInt32(centerOfPopulationStatus.SelectedValue),
                                          Convert.ToInt32(roadCategory.SelectedValue),
                                          Convert.ToInt32(region.SelectedValue),
                                          Convert.ToInt32(roadName.SelectedValue),
                                          Convert.ToInt32(roadValue.SelectedValue),
                                          Convert.ToInt32(participentAmmount.Text),
                                          Convert.ToInt32(vehicleAmmount.Text),
                                          Convert.ToInt32(accidentScheme.SelectedValue),
                                          Convert.ToInt32(accidentType.SelectedValue),
                                          additionalInfo.Text,
                                          Convert.ToInt32(centerStripWidth.Text),
                                          Convert.ToInt32(sidewalkWidth.Text),
                                          Convert.ToInt32(roadsideWidth.Text),
                                          Convert.ToInt32(roadWidth.Text),
                                          Convert.ToInt32(engineeringStructure.SelectedValue),
                                          Convert.ToInt32(planElement.SelectedValue),
                                          Convert.ToInt32(coverType.SelectedValue),
                                          Convert.ToInt32(roadState.SelectedValue),
                                          Convert.ToInt32(lightType.SelectedValue),
                                          Convert.ToInt32(whetherType.SelectedValue),
                                          Convert.ToInt32(roadCondition.SelectedValue));
        }

        private void btnAddVehicle_Click(object sender, EventArgs e)
        {
            VehicleForm vehicle = new VehicleForm(accidentCardId);
            vehicle.ShowDialog();
            LoadVehicleList(accidentCardId);            
        }

        private void btnAddPerson_Click(object sender, EventArgs e)
        {
            PersonForm person = new PersonForm(accidentCardId);
            person.ShowDialog();
            LoadPersonList(accidentCardId);
        }

        

        private void regionCode_Enter(object sender, EventArgs e)
        {            
            Rectangle rect = new Rectangle( 10,10, 1000,500 );
            imageViewer.ShowImage( frontPage, rect);
            
        }

        private void cardReportNumber_Enter(object sender, EventArgs e)
        {   
            Rectangle rect = new Rectangle(100, 100, 500, 500);
            imageViewer.ShowImage(frontPage, rect);
        }

        private void btnAddFrontImage_Click(object sender, EventArgs e)
        {
            if (accidentCardId == -1)
            {
                if (MessageBox.Show("Требуется сохранение. Продолжить?", "Внимание!", MessageBoxButtons.YesNo) == DialogResult.Yes)
                {
                    AccidentCard.CreateAccidentCard(ref accidentCardId);
                }
                else
                    return;
            }

            Stream myStream = null;

            openFileDialog.InitialDirectory = "c:\\";
            openFileDialog.Filter = "image files (*.jpg)|*.jpg|All files (*.*)|*.*";
            openFileDialog.FilterIndex = 2;
            openFileDialog.RestoreDirectory = true;

            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    if ((myStream = openFileDialog.OpenFile()) != null)
                    {
                        Bitmap image = new Bitmap(myStream);
                       
                        AccidentCard.UpdateAccidentCardFrontImage(accidentCardId, image); 
                       
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
                }
            }
        }

        private void btnAddBackImage_Click(object sender, EventArgs e)
        {
            if (accidentCardId == -1)
            {
                if (MessageBox.Show("Требуется сохранение. Продолжить?", "Внимание!", MessageBoxButtons.YesNo) == DialogResult.Yes)
                {
                    AccidentCard.CreateAccidentCard(ref accidentCardId);
                }
                else
                    return;
            }

            Stream myStream = null;

            openFileDialog.InitialDirectory = "c:\\";
            openFileDialog.Filter = "image files (*.jpg)|*.jpg|All files (*.*)|*.*";
            openFileDialog.FilterIndex = 2;
            openFileDialog.RestoreDirectory = true;

            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    if ((myStream = openFileDialog.OpenFile()) != null)
                    {
                        Bitmap image = new Bitmap(myStream);

                        AccidentCard.UpdateAccidentCardBackImage(accidentCardId, image);

                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
                }
            }
        }

        private void lbCars_SelectedIndexChanged(object sender, EventArgs e)
        {
            int vehicleID;
            if (vehicle_Map.TryGetValue(lbCars.SelectedIndex, out vehicleID))
            {
                VehicleForm vehicle = new VehicleForm(accidentCardId, vehicleID);
                vehicle.ShowDialog();
                LoadVehicleList(accidentCardId);
            }
        }

        private void lbPeople_SelectedIndexChanged(object sender, EventArgs e)
        {
            int personID;
            if (person_Map.TryGetValue(lbPeople.SelectedIndex, out personID))
            {
                PersonForm person = new PersonForm(accidentCardId, personID);
                person.ShowDialog();
                LoadPersonList(accidentCardId);
            }
        }

        private void checksum_Enter(object sender, EventArgs e)
        {
            Rectangle rect = new Rectangle(110, 10, 1000, 500);
            imageViewer.ShowImage(frontPage, rect);
        }

        private void cardRegistrationNumber_Enter(object sender, EventArgs e)
        {
            Rectangle rect = new Rectangle(210, 10, 1000, 500);
            imageViewer.ShowImage(frontPage, rect);
        }

        private void operationType_Enter(object sender, EventArgs e)
        {
            Rectangle rect = new Rectangle(310, 10, 1000, 500);
            imageViewer.ShowImage(frontPage, rect);
        }

        private void accidentDate_Enter(object sender, EventArgs e)
        {
            Rectangle rect = new Rectangle(410, 10, 1000, 500);
            imageViewer.ShowImage(frontPage, rect);
        }

        private void accidentTime_Enter(object sender, EventArgs e)
        {
            Rectangle rect = new Rectangle(510, 10, 1000, 500);
            imageViewer.ShowImage(frontPage, rect);
        }

        private void roadName_Enter(object sender, EventArgs e)
        {
            Rectangle rect = new Rectangle(610, 10, 1000, 500);
            imageViewer.ShowImage(frontPage, rect);
        }

        private void roadValue_Enter(object sender, EventArgs e)
        {
            Rectangle rect = new Rectangle(710, 10, 1000, 500);
            imageViewer.ShowImage(frontPage, rect);
        }

        private void distanceKm_Enter(object sender, EventArgs e)
        {
            Rectangle rect = new Rectangle(810, 10, 1000, 500);
            imageViewer.ShowImage(frontPage, rect);
        }

        private void distanceM_Enter(object sender, EventArgs e)
        {
            Rectangle rect = new Rectangle(910, 10, 1000, 500);
            imageViewer.ShowImage(frontPage, rect);
        }

        private void roadCategory_Enter(object sender, EventArgs e)
        {
            Rectangle rect = new Rectangle(1010, 10, 1000, 500);
            imageViewer.ShowImage(frontPage, rect);
        }

        private void region_Enter(object sender, EventArgs e)
        {
            Rectangle rect = new Rectangle(1110, 10, 1000, 500);
            imageViewer.ShowImage(frontPage, rect);
        }

        private void centerOfPopulationName_Enter(object sender, EventArgs e)
        {
            Rectangle rect = new Rectangle(1210, 10, 1000, 500);
            imageViewer.ShowImage(frontPage, rect);
        }

        private void centerOfPopulationStatus_Enter(object sender, EventArgs e)
        {
            Rectangle rect = new Rectangle(1310, 10, 1000, 500);
            imageViewer.ShowImage(frontPage, rect);
        }

        private void streetName_Enter(object sender, EventArgs e)
        {
            Rectangle rect = new Rectangle(1410, 10, 1000, 500);
            imageViewer.ShowImage(frontPage, rect);
        }

        private void streetCategory_Enter(object sender, EventArgs e)
        {
            Rectangle rect = new Rectangle(10, 110, 1000, 500);
            imageViewer.ShowImage(frontPage, rect);
        }

        private void house_Enter(object sender, EventArgs e)
        {
            Rectangle rect = new Rectangle(10, 210, 1000, 500);
            imageViewer.ShowImage(frontPage, rect);
        }

        private void accidentType_Enter(object sender, EventArgs e)
        {
            Rectangle rect = new Rectangle(10, 310, 1000, 500);
            imageViewer.ShowImage(frontPage, rect);
        }

        private void accidentScheme_Enter(object sender, EventArgs e)
        {
            Rectangle rect = new Rectangle(10, 410, 1000, 500);
            imageViewer.ShowImage(frontPage, rect);
        }

        private void vehicleAmmount_Enter(object sender, EventArgs e)
        {
            Rectangle rect = new Rectangle(10, 510, 1000, 500);
            imageViewer.ShowImage(frontPage, rect);
        }

        private void participentAmmount_Enter(object sender, EventArgs e)
        {
            Rectangle rect = new Rectangle(10, 610, 1000, 500);
            imageViewer.ShowImage(frontPage, rect);
        }

        private void planElement_Enter(object sender, EventArgs e)
        {
            Rectangle rect = new Rectangle(10, 710, 1000, 500);
            imageViewer.ShowImage(frontPage, rect);
        }

        private void engineeringStructure_Enter(object sender, EventArgs e)
        {
            Rectangle rect = new Rectangle(10, 810, 1000, 500);
            imageViewer.ShowImage(frontPage, rect);
        }

        private void roadWidth_Enter(object sender, EventArgs e)
        {
            Rectangle rect = new Rectangle(10, 910, 1000, 500);
            imageViewer.ShowImage(frontPage, rect);
        }

        private void roadsideWidth_Enter(object sender, EventArgs e)
        {
            Rectangle rect = new Rectangle(10, 1010, 1000, 500);
            imageViewer.ShowImage(frontPage, rect);
        }

        private void sidewalkWidth_Enter(object sender, EventArgs e)
        {
            Rectangle rect = new Rectangle(10, 1110, 1000, 500);
            imageViewer.ShowImage(frontPage, rect);
        }

        private void centerStripWidth_Enter(object sender, EventArgs e)
        {
            Rectangle rect = new Rectangle(10, 1210, 1000, 500);
            imageViewer.ShowImage(frontPage, rect);
        }

        private void coverType_Enter(object sender, EventArgs e)
        {
            Rectangle rect = new Rectangle(10, 1310, 1000, 500);
            imageViewer.ShowImage(frontPage, rect);
        }

        private void roadState_Enter(object sender, EventArgs e)
        {
            Rectangle rect = new Rectangle(10, 1410, 1000, 500);
            imageViewer.ShowImage(frontPage, rect);
        }

        private void lightType_Enter(object sender, EventArgs e)
        {
            Rectangle rect = new Rectangle(10, 1510, 1000, 500);
            imageViewer.ShowImage(frontPage, rect);
        }

        private void whetherType_Enter(object sender, EventArgs e)
        {
            Rectangle rect = new Rectangle(10, 1610, 1000, 500);
            imageViewer.ShowImage(frontPage, rect);
        }

        private void roadCondition_Enter(object sender, EventArgs e)
        {
            Rectangle rect = new Rectangle(10, 1710, 1000, 500);
            imageViewer.ShowImage(frontPage, rect);
        }

        private void additionalInfo_Enter(object sender, EventArgs e)
        {
            Rectangle rect = new Rectangle(10, 1810, 1000, 500);
            imageViewer.ShowImage(frontPage, rect);
        }

        private void AccidentCardForm_FormClosed(object sender, FormClosedEventArgs e)
        {
            imageViewer.Close();
        }
      
    }
}
